package com.lanyou.esb.cook.proxy.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lanyou.esb.cook.proxy.meta.Environment;

/**
 * http请求代理服务类
 * 
 * @author Davey.wu
 */
public class HttpProxyServlet extends HttpServlet {

	/****/
	private static final long serialVersionUID = 1089329690559350012L;

	/** HTTP请求代理 **/
	private Proxy proxy;

	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		super.init(servletConfig);
	}

	@Override
	public void destroy() {
		super.destroy();
	}

	@Override
	protected void service(HttpServletRequest servletRequest,
			HttpServletResponse servletResponse) throws ServletException,
			IOException {
		// 系统编码
		String systemCode = null;
		// 接口版本
		String ifVersion = null;
		// 接口编码
		String ifCode = null;
		try {
			/**
			 * 接口请求地址的统一规范格式:
			 * http://{domain}/{systemcode}/{version}/{interface_code
			 * }/{query_string}
			 ***/
			String[] patterns = servletRequest.getRequestURI().substring(1)
					.split("/");
			systemCode = patterns[0];
			ifVersion = patterns[1];
			ifCode = patterns[2];
		} catch (Exception e) {
			servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		// 处理请求
		proxy.process(servletRequest, servletResponse, this, systemCode,
				ifCode, ifVersion, Environment.PRODUCTION);
	}

	public Proxy getProxy() {
		return proxy;
	}

	public void setProxy(Proxy proxy) {
		this.proxy = proxy;
	}

}
